<template>
  <el-dialog :title="title" :visible.sync="visible" width="600px" append-to-body @close="handleClose">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="学员" prop="studentId">
            <el-select 
              v-model="form.studentId" 
              placeholder="请选择学员" 
              @change="handleStudentChange"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="student in studentOptions"
                :key="student.studentId"
                :label="student.name + '(' + student.studentNo + ')'"
                :value="student.studentId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="科目" prop="subjectId">
            <el-select 
              v-model="form.subjectId" 
              placeholder="请选择科目" 
              @change="handleSubjectChange"
              style="width: 100%"
            >
              <el-option
                v-for="subject in subjectOptions"
                :key="subject.subjectId"
                :label="subject.subjectName"
                :value="subject.subjectId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="考试时间" prop="examTime">
            <el-date-picker
              v-model="form.examTime"
              type="datetime"
              placeholder="选择考试时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成绩" prop="score">
            <el-input-number 
              v-model="form.score" 
              :min="0" 
              :max="100" 
              placeholder="请输入成绩"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="考试结果" prop="result">
            <el-radio-group v-model="form.result" @change="handleResultChange">
              <el-radio label="通过">通过</el-radio>
              <el-radio label="未通过">未通过</el-radio>
              <el-radio label="缺考">缺考</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="showAttemptInfo">
          <el-form-item label="考试次数">
            <el-input v-model="attemptInfo" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="form.remark" 
          type="textarea" 
          :rows="3"
          placeholder="请输入备注" 
        />
      </el-form-item>

      <!-- 历史考试记录 -->
      <el-form-item label="历史记录" v-if="historyRecords.length > 0">
        <el-table :data="historyRecords" size="mini" border>
          <el-table-column prop="attemptNo" label="次数" width="60" />
          <el-table-column prop="score" label="成绩" width="80" />
          <el-table-column prop="result" label="结果" width="80">
            <template slot-scope="scope">
              <el-tag :type="getResultTagType(scope.row.result)" size="mini">
                {{ scope.row.result }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="examTime" label="考试时间" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.examTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <!-- 补考安排信息 -->
      <el-form-item v-if="retakeInfo">
        <el-alert
          :title="retakeInfo"
          type="info"
          :closable="false"
          show-icon
        />
      </el-form-item>
    </el-form>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { registerExamRecord, updateExamRecord, getExamRecordsByStudentAndSubject, canTakeExam } from "@/api/jiaxiao/exam";
import { listStudent } from "@/api/jiaxiao/student";
import { listSubject } from "@/api/jiaxiao/subject";

export default {
  name: "ExamRecordDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: "登记考试记录"
    },
    editingRecord: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      form: {
        studentId: null,
        subjectId: null,
        score: null,
        result: null,
        examTime: null,
        remark: null
      },
      rules: {
        studentId: [
          { required: true, message: "请选择学员", trigger: "change" }
        ],
        subjectId: [
          { required: true, message: "请选择科目", trigger: "change" }
        ],
        result: [
          { required: true, message: "请选择考试结果", trigger: "change" }
        ],
        examTime: [
          { required: true, message: "请选择考试时间", trigger: "change" }
        ]
      },
      studentOptions: [],
      subjectOptions: [],
      historyRecords: [],
      attemptInfo: "",
      retakeInfo: "",
      showAttemptInfo: false,
      submitting: false
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.loadOptions();
        if (this.editingRecord) {
          this.form = { ...this.editingRecord };
          this.loadHistoryRecords();
        } else {
          this.resetForm();
        }
      }
    },
    editingRecord(val) {
      if (this.visible && val) {
        this.form = { ...val };
        this.loadHistoryRecords();
      }
    }
  },
  methods: {
    /** 加载选项数据 */
    loadOptions() {
      this.loadStudents();
      this.loadSubjects();
    },
    /** 加载学员选项 */
    loadStudents() {
      listStudent({}).then(response => {
        this.studentOptions = response.rows || [];
      });
    },
    /** 加载科目选项 */
    loadSubjects() {
      listSubject({}).then(response => {
        this.subjectOptions = response.rows || [];
      });
    },
    /** 学员选择变化 */
    handleStudentChange(studentId) {
      this.form.subjectId = null;
      this.historyRecords = [];
      this.attemptInfo = "";
      this.retakeInfo = "";
      this.showAttemptInfo = false;
    },
    /** 科目选择变化 */
    handleSubjectChange(subjectId) {
      if (this.form.studentId && subjectId) {
        this.loadHistoryRecords();
        this.checkCanTakeExam();
      }
    },
    /** 加载历史考试记录 */
    loadHistoryRecords() {
      if (!this.form.studentId || !this.form.subjectId) return;
      
      getExamRecordsByStudentAndSubject(this.form.studentId, this.form.subjectId).then(response => {
        this.historyRecords = response.data || [];
        this.updateAttemptInfo();
      });
    },
    /** 更新考试次数信息 */
    updateAttemptInfo() {
      const count = this.historyRecords.length;
      this.attemptInfo = `第${count + 1}次考试`;
      this.showAttemptInfo = count > 0;
    },
    /** 检查是否可以参加考试 */
    checkCanTakeExam() {
      if (!this.form.studentId || !this.form.subjectId) return;
      
      canTakeExam(this.form.studentId, this.form.subjectId).then(response => {
        if (!response.data) {
          this.retakeInfo = "该学员不满足考试条件，请检查学习进度";
        }
      });
    },
    /** 考试结果变化 */
    handleResultChange(result) {
      if (result === "未通过") {
        this.retakeInfo = "考试未通过，系统将自动安排补考";
      } else if (result === "通过") {
        this.retakeInfo = "考试通过，将更新学习进度状态";
      } else {
        this.retakeInfo = "";
      }
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.submitting = true;
        const isEdit = this.form && this.form.examId != null;
        const req = isEdit ? updateExamRecord(this.form) : registerExamRecord(this.form);
        req.then(() => {
          this.$modal.msgSuccess(isEdit ? "修改成功" : "考试记录登记成功");
          this.$emit('success');
          this.handleClose();
        }).catch(error => {
          this.$modal.msgError(error && error.message ? error.message : (isEdit ? "修改失败" : "登记失败"));
        }).finally(() => {
          this.submitting = false;
        });
      });
    },
    /** 关闭对话框 */
    handleClose() {
      this.$emit('update:visible', false);
    },
    /** 重置表单 */
    resetForm() {
      this.form = {
        studentId: null,
        subjectId: null,
        score: null,
        result: null,
        examTime: null,
        remark: null
      };
      this.historyRecords = [];
      this.attemptInfo = "";
      this.retakeInfo = "";
      this.showAttemptInfo = false;
      this.submitting = false;
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.resetFields();
      });
    },
    /** 获取结果标签类型 */
    getResultTagType(result) {
      switch(result) {
        case '通过': return 'success';
        case '未通过': return 'danger';
        case '缺考': return 'warning';
        default: return '';
      }
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
